package com.itheima.service.impl;

import com.itheima.common.entity.Result;
import com.itheima.dto.LoginDTO;
import com.itheima.mapper.MemberMapper;
import com.itheima.pojo.Member;
import com.itheima.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MemberMapper memberMapper;

    /**
     * 发送验证码
     * @param telephone
     */
    @Override
    public void sendValidateCode4Login(String telephone) {
        //生成验证码
        String validateCode = String.valueOf((int) ((Math.random() + 1) * 1000));
        //发送验证码
        //SMSUtils.sendMessage("瑞吉外卖","SMS_207860000",telephone,validateCode);
        //将验证码存到Redis中
        redisTemplate.opsForValue().set("validateCode1", validateCode);
        log.info("验证码：{}", validateCode);
        //定时删除验证码5分钟
        redisTemplate.expire("validateCode1", 5, java.util.concurrent.TimeUnit.MINUTES);
    }

    /**
     * 登录
     * @return
     * @param loginDTO
     */
    @Override
    public Result login(LoginDTO loginDTO) {
        //从Redis中获取验证码
        String redisCode = (String) redisTemplate.opsForValue().get("validateCode1");
        if (loginDTO.getValidateCode().equals(redisCode)) {
            if (memberMapper.findByTelephone(loginDTO.getTelephone()) == null) {
                Member member = new Member();
                member.setPhoneNumber(loginDTO.getTelephone());
                member.setRegTime(new Date());
                memberMapper.addMember(member);
            }
            //验证码正确
            return new Result(true, "验证码输入正确");
        } else {
            //验证码错误
            return new Result(false, "验证码输入错误");
        }
    }
}